package taewanme.gae.bookmark.dao;

import java.util.Date;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import taewanme.gae.bookmark.model.BookMark;

@Component("bookmarkDao")
public class BookmarkDaoJDOImpl {
	private Logger logger = LoggerFactory.getLogger(BookmarkDaoJDOImpl.class);
	
	@Autowired
	private PersistenceManagerFactory pmf;
	
	public BookMark save(BookMark bookMark){
		PersistenceManager pm = null;
		try{
			pm = pmf.getPersistenceManager();
			
			//if object is new 
			if(bookMark.getKey()==null){
				bookMark.setCreDate(new Date());
				Key key = KeyFactory.createKey(BookMark.class.getSimpleName(), bookMark.getUrl());
				bookMark.setKey(key);
			}
			bookMark.setUptDate(new Date());
			
			bookMark = pm.makePersistent(bookMark);
			BookMark deteached = pm.detachCopy(bookMark);
			return deteached;
		}finally{
			pm.close();
		}
	}
	
	public BookMark get(String url){
		Key key = KeyFactory.createKey(BookMark.class.getSimpleName(), url);
		PersistenceManager pm = null;
		try{
			pm = pmf.getPersistenceManager();
			BookMark bookMark = pm.getObjectById(BookMark.class, key);
			
			logger.error("before:"+bookMark.toString());
			BookMark deteached = pm.detachCopy(bookMark);
			logger.error("after:"+deteached.toString());			
			return deteached;
		}catch(JDOObjectNotFoundException e){
			logger.warn("Bookmark retrieve error: url ");
			throw e;
		}finally{
			pm.close();
		}
		
	}
	
	public void remove(Key key){
		PersistenceManager pm = null;
		try{
			pm = pmf.getPersistenceManager();
			BookMark bookmark = pm.getObjectById(BookMark.class, key);
			pm.deletePersistent(bookmark);
			
		}catch (Exception e) {
			logger.error("Delete Error:"+key);
		}finally{
			pm.close();
		}
	}
	
	
}
